package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.compete;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.PdtAuthDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.TCompeteDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteDdetailExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompetePdtAuthExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.TCompeteServiceImpl;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetCompeteCompanyVo;
import com.xiaoxu.intranetweb.util.SzResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CompeteBu {
    @Autowired
    private TCompeteServiceImpl tCompeteService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private ICCompanysService icCompanysService;
    @Autowired
    private ISysUserOrgConnService iSysUserOrgConnService;
    @Autowired
    private ISysFilesService fileBu;
    @Autowired
    private ITCompeteDetailService tCompeteDetailService;
    @Autowired
    private ICProductsInfoService icProductsInfoService;
    @Autowired
    private ISysUserPlantConnService iSysUserPlantConnService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private TCompeteDic tCompeteDic;
    @Autowired
    private CompeteDetailBu competeDetailBu;
    @Autowired
    private ITCompeteTenderService tCompeteTenderService;
    @Autowired
    private TCompetePdtsAuthService tCompetePdtsAuthService;
    @Autowired
    private ICTrucksService icTrucksService;
    @Autowired
    private ITApproveService tApproveService;
    @Autowired
    private ITApproveInfoService tApproveInfoService;
    @Autowired
    private PdtAuthDic pdtAuthDic;
    @Autowired
    private ITSpecialPriceTypeService specialPriceTypeService;
    @Autowired
    private ITSpecialPriceService tSpecialPriceService;
    @Autowired
    private ITCompeteTenderService iTCompeteTenderService;

    //查询招标信息
    public SzResult getCompete(String page, String pageSize, String id, String title, String startTime, String endTime, String minBid, List status, String archived, String token, String plantId
    ) throws Exception {
        List<TCompete> competeList;
//        String plantId = null;
//        if (token != null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }
        Map<String, Object> map = new HashMap<>();
        if (page == null && pageSize == null) {
            QueryWrapper<TCompete> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DEL_FLAG", 0);
            queryWrapper.eq(id != null && !id.isEmpty(), "ID", id);
            queryWrapper.like(title != null && !title.isEmpty(), "TITLE", title);
            queryWrapper.between(startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty(), "CREATE_DATE", startTime, endTime);
            queryWrapper.eq(minBid != null && !minBid.isEmpty(), "MIN_BID", minBid);
            if (status != null && !status.toString().isEmpty()) {
                if (status.size() > 1) {
                    String a = (String) status.get(0);
                    String b = (String) status.get(1);
                    queryWrapper.between(!a.isEmpty() && !b.isEmpty(), "STATUS", a, b);
                } else if (status.size() == 1) {
                    Object a = status.get(0);
                    queryWrapper.eq(!a.equals(""), "STATUS", a);
                }
            }
            queryWrapper.eq(archived != null && !archived.isEmpty(), "ARCHIVED", archived);
            queryWrapper.eq(plantId != null && !plantId.isEmpty(), "DATA_FROM", plantId);
            queryWrapper.orderByDesc("CREATE_DATE");
            competeList = tCompeteService.list(queryWrapper);
            map.put("total", competeList.size());
        } else {
            Page<TCompete> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
            QueryWrapper<TCompete> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DEL_FLAG", 0);
            queryWrapper.eq(id != null && !id.equals(""), "ID", id);
            queryWrapper.like(title != null && !title.equals(""), "TITLE", title);
            queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "CREATE_DATE", startTime, endTime);
            queryWrapper.eq(minBid != null && !minBid.equals(""), "MIN_BID", minBid);
            if (status != null && !status.toString().equals("")) {
                if (status.size() == 1) {
                    Object a = status.get(0);
                    queryWrapper.eq(!a.equals(""), "STATUS", a);
                } else {
                    Object a = status.get(0);
                    Object b = status.get(1);
                    queryWrapper.between(!a.equals("") && !b.equals(""), "STATUS", a, b);
                }
            }
            queryWrapper.eq(archived != null && !archived.equals(""), "ARCHIVED", archived);
            queryWrapper.orderByDesc("CREATE_DATE");
            queryWrapper.eq("DATA_FROM", plantId);
            IPage<TCompete> competeList2 = tCompeteService.page(page1, queryWrapper);
            competeList = competeList2.getRecords();
            map.put("total", page1.getTotal());
        }
        List<GetCompeteCompanyVo> getCompeteCompanyVos = new ArrayList<>();
        //将competeList里的每个数据的createCpy拿出来，查询companys表的CPY_CODE，然后放到getCompeteCompanyVos里，getCompeteCompanyVos的其他字段也从competeList里拿
        for (TCompete tCompete : competeList) {
            GetCompeteCompanyVo getCompeteCompanyVo = new GetCompeteCompanyVo();
            getCompeteCompanyVo.setId(tCompete.getId());
            getCompeteCompanyVo.setTitle(tCompete.getTitle());
            getCompeteCompanyVo.setContent(tCompete.getContent());
            getCompeteCompanyVo.setBeginDate(tCompete.getBeginDate());
            getCompeteCompanyVo.setBeginTDate(tCompete.getBeginTDate());
            if (tCompete.getCreateBy() != null && !tCompete.getCreateBy().equals("")) {
                getCompeteCompanyVo.setCreateBy(userInfoDao.getUser(tCompete.getCreateBy()).getTrueName());
            } else {
                getCompeteCompanyVo.setCreateBy("");
            }
            if (tCompete.getAuditorId() != null && !tCompete.getAuditorId().equals("")) {
                getCompeteCompanyVo.setAuditorName(userInfoDao.getUser(tCompete.getAuditorId()).getTrueName());
            } else {
                getCompeteCompanyVo.setAuditorName("");
            }
            getCompeteCompanyVo.setAuditTime(tCompete.getAuditTime());
            getCompeteCompanyVo.setCreateDate(tCompete.getCreateDate());
            getCompeteCompanyVo.setMinBid(tCompete.getMinBid());
            getCompeteCompanyVo.setBidType(tCompete.getBidType());
            getCompeteCompanyVo.setStatus(tCompete.getStatus());
            if (tCompete.getStatus()!=null && tCompete.getStatus()>9 && tCompete.getStatus()<100){
                getCompeteCompanyVo.setIfApproval("通过");
            } else if (tCompete.getStatus() != null && tCompete.getStatus() < 9) {
                getCompeteCompanyVo.setIfApproval("未审批");
            }
            else {
                getCompeteCompanyVo.setIfApproval("驳回");
            }
            getCompeteCompanyVo.setArchived(tCompete.getArchived());
            getCompeteCompanyVo.setCreateCpy(tCompete.getCreateCpy());
            getCompeteCompanyVo.setOpenMinBid(tCompete.getOpenMinBid());
            getCompeteCompanyVo.setPriceShow(tCompete.getPriceShow());
            getCompeteCompanyVo.setNegativeBidding(tCompete.getNegativeBidding());
            getCompeteCompanyVo.setExecuteEndTime(tCompete.getExecuteEndTime());
            getCompeteCompanyVo.setExecuteStartTime(tCompete.getExecuteStartTime());
            CCompanys companys = icCompanysService.getById(tCompete.getCreateCpy());
            getCompeteCompanyVo.setCpyName(companys.getCpyCo() + "." + companys.getCpyChico());
            QueryWrapper<SysFiles> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("CONN_ID", tCompete.getId());
            List<SysFiles> fileList = fileBu.list(queryWrapper1);
            getCompeteCompanyVo.setFileList(fileList);
            getCompeteCompanyVos.add(getCompeteCompanyVo);
        }
        map.put("list", getCompeteCompanyVos);
        return SzResult.success(map);
    }

    //   审批，就是将status变成10
    public SzResult approveCompete(
            String id,
            Integer status,
            String token,
            String plantId) throws Exception {
        QueryWrapper<TCompete> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        TCompete Compete1 = tCompeteService.getOne(queryWrapper);
        if (Compete1.getStatus()>9 && Compete1.getStatus()<100){

            return SzResult.Error("已经审批过了");
        }
        SysUser  user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        TCompete Compete = tCompeteService.getById(id);
        Compete.setStatus(status);
        Compete.setAuditorId(user.getId());
        Compete.setAuditTime(LocalDateTime.now());
        tCompeteService.updateById(Compete);
        return SzResult.Success();
    }

    //增加招标信息
    public SzResult addCompete(String title, String beginDate, String beginTDate,String executeStartTime,String executeEndTime, String content, Integer bidType,String minBid, String archived,
                               String openMinBid, String priceShow, Integer negativeBidding,String token, String plantId) throws Exception {
//        if(bidType==2){
////            暂不支持发布数量竞标类型
//            return SzResult.error("暂不支持发布数量竞标类型");
//        }
        TCompete tCompete = new TCompete();
        if (title != null && !title.equals("")) {
            tCompete.setTitle(title);
        }
        if (beginDate != null && !beginDate.equals("")) {
            tCompete.setBeginDate(LocalDateTime.parse(beginDate.replace(" ", "T")));
        }
        if (negativeBidding != null) {
            tCompete.setNegativeBidding(negativeBidding);
        }
        if (beginTDate != null && !beginTDate.equals("")) {
            tCompete.setBeginTDate(LocalDateTime.parse(beginTDate.replace(" ", "T")));
        }
        if (content != null && !content.equals("")) {
            tCompete.setContent(content);
        }
        tCompete.setExecuteStartTime(executeStartTime);
        tCompete.setExecuteEndTime(executeEndTime);
        tCompete.setCreateDate(LocalDateTime.now());

        if (minBid != null && !minBid.equals("")) {
            if (openMinBid != null && openMinBid.equals("1")) {
                tCompete.setMinBid(Double.valueOf(minBid));
            } else {
                return SzResult.error("请先开启最小投标量");
            }
        }
        tCompete.setStatus(1);
//0未归档 1已归档
        if (archived != null && !archived.equals("")) {
            tCompete.setArchived(Integer.valueOf(archived));
        } else {
            tCompete.setArchived(0);
        }
        tCompete.setBidType(bidType);
        tCompete.setDelFlag(0);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<SysUserOrgConn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_ID", user1.getId());
        SysUserOrgConn sysUserOrgConn = iSysUserOrgConnService.getOne(queryWrapper);
        tCompete.setCreateCpy(sysUserOrgConn.getOrgId());
//        QueryWrapper<SysUserPlantConn> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("USER_ID", user1.getId());
//        SysUserPlantConn sysUserPlantConn = iSysUserPlantConnService.getOne(queryWrapper1);
        tCompete.setDataFrom(plantId);
        //是否开启最小投标量 0未开启 1开启,默认为不开启
        if (openMinBid != null && !openMinBid.equals("")) {
            tCompete.setOpenMinBid(Integer.valueOf(openMinBid));
        } else {
            tCompete.setOpenMinBid(0);
        }
        if (priceShow != null && !priceShow.equals("")) {
            tCompete.setPriceShow(Integer.valueOf(priceShow));
        } else {
            tCompete.setPriceShow(0);
        }

        tCompete.setCreateBy(user1.getId());
        tCompeteService.save(tCompete);
        sysLogBu.logRecord("新增竞标信息", user1.getTrueName(), "新增了" + title + "的竞标信息", plantId);
        String id = tCompete.getId();
        return SzResult.success(id);

    }

    //撤销招标信息
    public SzResult delCompete(String id, String token, String plantId) throws Exception {
        TCompete tCompete = tCompeteService.getById(id);
        if (tCompete.getBeginDate().isBefore(LocalDateTime.now())) {
            return SzResult.error("投标时间已截止，无法撤销！");
        }
        Duration duration = java.time.Duration.between(tCompete.getBeginTDate(), LocalDateTime.now());//开始时间
        Duration duration1 = java.time.Duration.between(tCompete.getBeginDate(), LocalDateTime.now());//结束时间
        if (duration.toMinutes() >= 0 && duration1.toMinutes() < 0) {
            return SzResult.error("投标时间正在开始，无法撤销！");
        }
        if (duration.toMinutes() > -5 && duration1.toMinutes() < 0) {
            return SzResult.error("距起投时间不足5分钟，无法撤销！");
        }
        if (duration.toMinutes() >= 0 && duration1.toMinutes() >= 0) {
            return SzResult.error("投标时间已截止，无法撤销！");
        }
        tCompete.setDelFlag(1);
        tCompeteService.updateById(tCompete);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("撤销竞标信息", user1.getTrueName(), "撤销了【" + tCompete.getTitle() + "】的竞标信息", plantId);
        return SzResult.Success();
    }

    //修改招标信息
    public SzResult updateCompete(String id, String title, String content,Integer bidType, String beginDate,
                                  String beginTDate, String executeStartTime,String executeEndTime,String minBid, String status, String openMinBid, String priceShow, Integer negativeBidding, String token, String plantId) throws Exception {
        TCompete tCompete1 = tCompeteService.getById(id);
        if (tCompete1.getBeginDate() == null || tCompete1.getBeginTDate() == null) {
            return SzResult.error("开始时间或结束时间为空，不可修改");
        }
//判断一下是否结束
        if (tCompete1.getBeginDate().compareTo(LocalDateTime.now()) < 0) {
            return SzResult.error("投标时间已截止，无法修改！");
        }
        Duration duration = java.time.Duration.between(tCompete1.getBeginTDate(), LocalDateTime.now());//开始时间
        Duration duration1 = java.time.Duration.between(tCompete1.getBeginDate(), LocalDateTime.now());//结束时间
        if (duration.toMinutes() >= 0 && duration1.toMinutes() < 0) {
            return SzResult.error("投标时间正在开始，无法修改！");
        }
        //        开始时间不能小于结束时间
        if (beginDate != null && !beginDate.equals("") && beginTDate != null && !beginTDate.equals("")) {
            if (beginDate.compareTo(beginTDate) < 0) {
                return SzResult.error("开始时间不能小于结束时间");
            }
        }
        if (duration.toMinutes() > -5 && duration1.toMinutes() < 0) {
            return SzResult.error("距起投时间不足5分钟，无法修改！");
        }
        if (duration.toMinutes() >= 0 && duration1.toMinutes() >= 0) {
            return SzResult.error("投标时间已截止，无法修改！");
        }
        TCompete tCompete = new TCompete();
        tCompete.setId(id);
        if (title != null && !title.equals("")) {
            tCompete.setTitle(title);
        }
        if (content != null && !content.equals("")) {
            tCompete.setContent(content);
        }
        tCompete.setCreateDate(LocalDateTime.now());
        if (beginDate != null && !beginDate.equals("")) {
            tCompete.setBeginDate(LocalDateTime.parse(beginDate.replace(" ", "T")));
        }
        if (beginTDate != null && !beginTDate.equals("")) {
            tCompete.setBeginTDate(LocalDateTime.parse(beginTDate.replace(" ", "T")));
        }
        if (minBid != null && !minBid.equals("")) {
            Integer openMinBid1 = tCompete1.getOpenMinBid();
            if (openMinBid1 == 1) {
                tCompete.setMinBid(Double.valueOf(minBid));
            } else {
                return SzResult.error("请先开启最低投标限制");
            }
        }
        if (status != null && !status.equals("")) {
            tCompete.setStatus(Integer.valueOf(status));
        }
        if (openMinBid != null && !openMinBid.equals("")) {
            tCompete.setOpenMinBid(Integer.valueOf(openMinBid));
        }
        if (priceShow != null && !priceShow.equals("")) {
            tCompete.setPriceShow(Integer.valueOf(priceShow));
        }
        tCompete.setExecuteStartTime(executeStartTime);
        tCompete.setExecuteEndTime(executeEndTime);
        tCompete.setBidType(bidType);
        tCompete.setNegativeBidding(negativeBidding);
        tCompeteService.updateById(tCompete);
        SysUser user1 = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("修改竞标信息", user1.getTrueName(), "修改了【" + title + "】的竞标信息", plantId);
        return SzResult.Success();
    }

    //    导出所有竞标excel
    @Async
    public Future<List<CompeteExcelEn>> exportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String token, String title, String startTime, String endTime, String minBid, String Status, String archived, String plantId) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<CompeteExcelEn> competeExcelEns = new ArrayList<>();
// 判断 mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                                newId.put("id", id.get("id"));
                            }
                        }
                        newIds.add(newId);
                    }
//            newIds为Map<String, Object>类型，需要转换为PoundQueryExcelBo类型
//            遍历newIds
                    for (Map<String, Object> newId : newIds) {
//                创建一个PoundQueryExcelBo对象
                        CompeteExcelEn competeExcelEn = CompeteExcelEn.builder().build();
//                遍历newId
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
//                    判断entry的key是否为"poundDate"，是的话，将entry的value转换为LocalDateTime类型，再赋值给poundQueryExcelBo的poundDate
                            if (entry.getKey().equals("title")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setTitle("");
                                } else {
                                    competeExcelEn.setTitle(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("content")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setContent("");
                                } else {
                                    competeExcelEn.setContent(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createBy")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setCreateBy("");
                                } else {
                                    competeExcelEn.setCreateBy(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createDate")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setCreateDate("");
                                } else {
                                    competeExcelEn.setCreateDate(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("beginDate")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setBeginDate("");
                                } else {
                                    competeExcelEn.setBeginDate(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("beginTDate")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setBeginTDate("");
                                } else {
                                    competeExcelEn.setBeginTDate(entry.getValue().toString());
                                }
                            }
//                            executeStartTime
                            if (entry.getKey().equals("executeStartTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setExecuteStartTime("");
                                } else {
                                    competeExcelEn.setExecuteStartTime(entry.getValue().toString());
                                }
                            }
//                            executeEndTime
                            if (entry.getKey().equals("executeEndTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setExecuteEndTime("");
                                } else {
                                    competeExcelEn.setExecuteEndTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("cpyName")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setCpyName("");
                                } else {
                                    competeExcelEn.setCpyName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("status")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setStatus("");
                                } else {
                                    competeExcelEn.setStatus(tCompeteDic.getStatusDic(Integer.valueOf(entry.getValue().toString())));
                                }
                            }
                            if (entry.getKey().equals("bidType")) {
                                String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue().equals(""));
                                if (value.isEmpty()) {
                                    competeExcelEn.setBidType("");
                                } else {
                                    competeExcelEn.setBidType(Integer.parseInt(value) == 1 ? "车数" : "数量");
                                }
                            }
                            if (entry.getKey().equals("openMinBid")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setOpenMinBid(null);
                                } else {
                                    competeExcelEn.setOpenMinBid(new BigDecimal(tCompeteDic.getOpenMinBidDic(Integer.valueOf(entry.getValue().toString()))));
                                }
                            }
                            if (entry.getKey().equals("priceShow")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setPriceShow(null);
                                } else {
                                    competeExcelEn.setPriceShow(new BigDecimal(tCompeteDic.getPriceShowDic(Integer.valueOf(entry.getValue().toString()))));
                                }
                            }
                            if (entry.getKey().equals("id")) {
                                if (this.getompeteDdetailById(entry.getValue().toString()) != null) {
                                    competeExcelEn.setItems(this.getompeteDdetailById(entry.getValue().toString()).toString().replace("[", "").replace("]", ""));
                                } else {
                                    competeExcelEn.setItems("");
                                }
                            }
                        }
//                存入poundQueryExcelBos
                        competeExcelEns.add(competeExcelEn);
                    }
                    break;
                case "all":
//                    为全部时直接调用查询方法
//                    String plantId = null;
//                    if (token != null) {
//                        plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//                    }
                    QueryWrapper<TCompete> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("DEL_FLAG", 0);
                    queryWrapper.like(title != null && !title.equals(""), "TITLE", title);
                    queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "CREATE_DATE", startTime, endTime);
                    queryWrapper.eq(minBid != null && !minBid.equals(""), "MIN_BID", minBid);
                    queryWrapper.like(Status != null && !Status.equals(""), "STATUS", Status);
                    queryWrapper.eq(archived != null && !archived.equals(""), "ARCHIVED", archived);
                    queryWrapper.eq(plantId != null && !plantId.equals(""), "DATA_FROM", plantId);
                    queryWrapper.orderByDesc("CREATE_DATE");
                    List<TCompete> competeList = tCompeteService.list(queryWrapper);
//                    遍历cWeightSheets匹配到对应的字段
                    for (TCompete compete : competeList) {
//                     创建一个PoundQueryExcelBo对象
                        CompeteExcelEn competeExcelEn = CompeteExcelEn.builder()
                                .title(Optional.ofNullable(compete.getTitle()).orElse(""))
                                .content(Optional.ofNullable(compete.getContent()).orElse(""))
                                .createBy(Optional.of(this.getUserName(compete.getCreateBy())).map(Object::toString).orElse(""))
                                .createDate(Optional.of(compete.getCreateDate()).map(Object::toString).orElse(""))
                                .cpyName(Optional.of(this.getCompany(compete.getCreateCpy()).getCpyCo()).map(Object::toString).orElse(""))
                                .status(Optional.of(tCompeteDic.getStatusDic(compete.getStatus())).map(Object::toString).orElse(""))
                                .beginDate( Optional.of(compete.getBeginDate()).map(Object::toString).orElse(""))
                                .beginTDate(Optional.of(compete.getBeginTDate()).map(Object::toString).orElse(""))
                                .executeStartTime(Optional.of(compete.getExecuteStartTime()).map(Object::toString).orElse(""))
                                .executeEndTime(Optional.of(compete.getExecuteEndTime()).map(Object::toString).orElse(""))
                                .bidType(
                                        compete.getBidType().toString().isEmpty()
                                        ? ""
                                        : compete.getBidType().toString().equals("1") ? "车数" : compete.getBidType().toString().equals("2") ? "数量" : ""
                                   )
                                .openMinBid(new BigDecimal(tCompeteDic.getOpenMinBidDic(compete.getOpenMinBid()) != null ? tCompeteDic.getOpenMinBidDic(compete.getOpenMinBid()) : "0"))
                                .priceShow(new BigDecimal(tCompeteDic.getPriceShowDic(compete.getPriceShow()) != null ? tCompeteDic.getPriceShowDic(compete.getPriceShow()) : "0"))
                                .items(this.getompeteDdetailById(compete.getId()).toString().replace("[", "").replace("]", ""))
                                .build();
//                    存入poundQueryExcelBos
                        competeExcelEns.add(competeExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//            newIds为Map<String, Object>类型，需要转换为PoundQueryExcelBo类型
//            遍历newIds
                    for (Map<String, Object> newId : newIds) {
//                创建一个PoundQueryExcelBo对象
                        CompeteExcelEn competeExcelEn = CompeteExcelEn.builder().build();
//                遍历newId
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
//                    判断entry的key是否为"poundDate"，是的话，将entry的value转换为LocalDateTime类型，再赋值给poundQueryExcelBo的poundDate
                            if (entry.getKey().equals("title")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setTitle("");
                                } else {
                                    competeExcelEn.setTitle(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("content")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setContent("");
                                } else {
                                    competeExcelEn.setContent(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createBy")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setCreateBy("");
                                } else {
                                    competeExcelEn.setCreateBy(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createDate")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setCreateDate("");
                                } else {
                                    competeExcelEn.setCreateDate(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("beginDate")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setBeginDate("");
                                } else {
                                    competeExcelEn.setBeginDate(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("beginTDate")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setBeginTDate("");
                                } else {
                                    competeExcelEn.setBeginTDate(entry.getValue().toString());
                                }
                            }
                            //                            executeStartTime
                            if (entry.getKey().equals("executeStartTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setExecuteStartTime("");
                                } else {
                                    competeExcelEn.setExecuteStartTime(entry.getValue().toString());
                                }
                            }
//                            executeEndTime
                            if (entry.getKey().equals("executeEndTime")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setExecuteEndTime("");
                                } else {
                                    competeExcelEn.setExecuteEndTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("cpyName")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setCpyName("");
                                } else {
                                    competeExcelEn.setCpyName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("status")) {
                                competeExcelEn.setStatus(tCompeteDic.getStatusDic(Integer.valueOf(entry.getValue().toString())));
                            }
                            if (entry.getKey().equals("bidType")) {
                                String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue().equals(""));
                                if (value.isEmpty()) {
                                    competeExcelEn.setBidType("");
                                } else {
                                    competeExcelEn.setBidType(Integer.parseInt(value) == 1 ? "车数" : "数量");
                                }
                            }
                            if (entry.getKey().equals("openMinBid")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setOpenMinBid(null);
                                } else {
                                    competeExcelEn.setOpenMinBid(new BigDecimal(tCompeteDic.getOpenMinBidDic(Integer.valueOf(entry.getValue().toString()))));
                                }
                            }
                            if (entry.getKey().equals("priceShow")) {
                                if (entry.getValue() == null || entry.getValue().equals("")
                                ) {
                                    competeExcelEn.setPriceShow(null);
                                } else {
                                    competeExcelEn.setPriceShow(new BigDecimal(tCompeteDic.getPriceShowDic(Integer.valueOf(entry.getValue().toString()))));
                                }
                            }
//                            List    <com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteDdetailExcelEn>
                            if (entry.getKey().equals("id")) {
                                if (this.getompeteDdetailById(entry.getValue().toString()) != null) {
                                    competeExcelEn.setItems(this.getompeteDdetailById(entry.getValue().toString()).toString().replace("[", "").replace("]", ""));
                                } else {
                                    competeExcelEn.setItems("");
                                }
                            }
                        }
//                存入poundQueryExcelBos
                        competeExcelEns.add(competeExcelEn);
                    }
                    break;
                default:
                    break;
            }
            return new AsyncResult<>(competeExcelEns);
        } catch (Exception e) {
//使用slf4j打印异常信息：导出poundQueryExcelBos失败
            log.error("导出competeExcelEns失败", e);
            return null;
        }
    }

    //根据id查询竞价信息
    public List<Map<String, String>> getompeteDdetailById(String id) {
        QueryWrapper<TCompeteDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("COMPETE_ID", id);
        queryWrapper.eq("DEL_FLAG", 0);
        List<TCompeteDetail> tCompeteDetails = tCompeteDetailService.list(queryWrapper);
        List<Map<String, String>> competeDdetailExcelEns = new ArrayList<>();
        for (TCompeteDetail tCompeteDetail : tCompeteDetails) {
            CompeteDdetailExcelEn competeDdetailExcelEn = CompeteDdetailExcelEn.builder()
                    .pdtId(Optional.ofNullable(tCompeteDetail.getPdtId()).orElse(""))
                    .pdtWeight(Optional.ofNullable(tCompeteDetail.getPdtWeight()).map(Object::toString).orElse(""))
                    .pdtPrice(tCompeteDetail.getPdtPrice())
                    .minBid(BigDecimal.valueOf(tCompeteDetail.getMinBid()))
                    .build();
            Map<String, String> map = new HashMap<>();
            QueryWrapper<CProductsInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ID", competeDdetailExcelEn.getPdtId());
            queryWrapper1.eq("PDTINF_DELETED", 0);
            CProductsInfo cProductsInfo = icProductsInfoService.getOne(queryWrapper1);
            if (cProductsInfo != null) {
                map.put("品种", cProductsInfo.getPdtinfPdt());
            }
            map.put("预产量", competeDdetailExcelEn.getPdtWeight());
            map.put("底价", competeDdetailExcelEn.getPdtPrice().toString());
            map.put("底量", competeDdetailExcelEn.getMinBid().toString());
            competeDdetailExcelEns.add(map);
        }
        return competeDdetailExcelEns;
    }

    //获取单位
    public CCompanys getCompany(String id) {
        QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("CPY_DELETED", 0);
        return icCompanysService.getOne(queryWrapper);
    }

    //    获取人员姓名
    public String getUserName(String id) {
        try {
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ID", id);
            queryWrapper.eq("DEL_FLAG", 0);
            SysUser sysUser = iSysUserService.getOne(queryWrapper);
            return sysUser.getTrueName();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 待开标按钮
     */
    public SzResult openCompete(String id, String token, String plantId) throws Exception {
        TCompete compete = tCompeteService.getById(id);
        String title = compete.getTitle();
        LocalDateTime beginDate = compete.getBeginDate();//标段结束时间
        LocalDateTime now = LocalDateTime.now();//当前时间
        if (beginDate.isAfter(now)) {
            return SzResult.error("开启待开标失败，标段结束时间未到");
        }
        //31-40开标中
        Integer status = compete.getStatus();
        //status在31-40之间
        if (status >= 31 && status <= 40) {
            return SzResult.error("该标已待开标");
        }
        if (status >= 41 && status <= 50) {
            return SzResult.error("该标已开标");
        }
        if (status >= 51 && status <= 60) {
            return SzResult.error("该标已定标");
        }
        compete.setStatus(31);
        tCompeteService.updateById(compete);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        sysLogBu.logRecord("竞标", user.getTrueName(), "开启了标题为" + "【+" + title + "】" + "的标", plantId);
        return SzResult.Success();
    }

    /**
     * 延时投标
     */
    public SzResult delayedBid(String id, String delayedTime, String reason, String token, String plantId) throws Exception {
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        //1、只有开标中的标段才能延时投标,31-40开标中
        QueryWrapper<TCompete> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.between("STATUS", 31, 40);
        TCompete compete = tCompeteService.getOne(queryWrapper);
        if (compete == null) {
            return SzResult.Error("该标段已开标，无法延时投标");
        }
        if (reason == null || reason.isEmpty()) {
            return SzResult.Error("请输入延时理由");
        }
        //3、达到三家投标公司，修改标段结束时间,延时投标,并将状态改为21
        LocalDateTime beginDate = compete.getBeginDate();
        //data是延时的时间,如:1,0.5.单位是小时
        LocalDateTime newBeginDate = beginDate.plusHours(Long.parseLong(delayedTime));
        compete.setBeginDate(newBeginDate);
        compete.setStatus(21);
        tCompeteService.updateById(compete);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        sysLogBu.logRecord("延时投标", user.getTrueName(), "延时了标题为" + "【title】" + "的标" + "。投标结束时间从" + beginDate + "延时至" + newBeginDate + "延时理由为【" + reason + "】", plantId);
        return SzResult.success("成功延时投标！");
    }


    /**
     * 开标
     */
    public SzResult evaluateBid(String id, String token, String plantId) throws Exception {
        TCompete compete = tCompeteService.getById(id);
        String title = compete.getTitle();
        LocalDateTime beginDate = compete.getBeginDate();//标段结束时间
        LocalDateTime now = LocalDateTime.now();//当前时间
        if (beginDate.isAfter(now)) {
            return SzResult.error("开标失败，标段结束时间未到");
        }
        //31-40开标中
        Integer status = compete.getStatus();
        //status在41-50之间
        if (status >= 51 && status <= 60) {
            return SzResult.error("该标已定标");
        }
        if (status >= 41 && status <= 50) {
            return SzResult.error("该标已开标");
        }
        if (status < 31) {
            return SzResult.error("该标未待开标");
        }
        compete.setStatus(41);
        tCompeteService.updateById(compete);
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        sysLogBu.logRecord("竞标", user.getTrueName(), "将标题为" + "【+" + title + "】" + "的标的状态设置为开标", plantId);
        return SzResult.Success();
    }

    /**
     * 定标
     */
    public SzResult fixedBid(String id, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        TCompete compete = tCompeteService.getById(id);
        String title = compete.getTitle();
        Integer status = compete.getStatus();
        LocalDateTime beginDate = compete.getBeginDate();//标段结束时间
        LocalDateTime now = LocalDateTime.now();//当前时间
        if (beginDate.isAfter(now)) {
            return SzResult.error("定标失败，标段结束时间未到");
        }
        if (status >= 31 && status <= 40) {
            return SzResult.error("该标未开标");
        }
        if (status < 31) {
            return SzResult.error("该标未待开标");
        }
        if (status >= 51 && status <= 60) {
            return SzResult.error("该标已定标");
        }
        compete.setStatus(51);
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TCompeteTender> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("COMPETE_ID", id);
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        List<TCompeteTender> tCompeteTenderList = tCompeteTenderService.list(queryWrapper);

        for (TCompeteTender tCompeteTender : tCompeteTenderList) {
            if (tCompeteTender.getWinBid() == null || tCompeteTender.getWinBid().equals("0")) {
                tCompeteTender.setWinBid("2");
                tCompeteTenderService.updateById(tCompeteTender);
            }
        }
//        往定价表写数据
//        先查出中了哪些标
        QueryWrapper<TCompeteTender> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("COMPETE_ID", id);
        queryWrapper1.eq("DEL_FLAG", 0);
        queryWrapper1.eq("DATA_FROM", plantId);
        queryWrapper1.eq("WIN_BID",1);
        List<TCompeteTender> competeTenders = iTCompeteTenderService.list(queryWrapper1);
        for (TCompeteTender competeTender:competeTenders) {
            TSpecialPrice tSpecialPrice = new TSpecialPrice();
            tSpecialPrice.setNum(competeTender.getWinBidWeight());
            tSpecialPrice.setResidueNum(competeTender.getWinBidWeight());
            tSpecialPrice.setPriceTypeId("029eaff510c911ef823f00ff8a757bed");
            TSpecialPriceType tSpecialPriceType = specialPriceTypeService.getById("029eaff510c911ef823f00ff8a757bed");
            tSpecialPrice.setPriceType(tSpecialPriceType.getPriceTypeName());
            tSpecialPrice.setCoId(competeTender.getCpyId());
            tSpecialPrice.setPdtId(competeTender.getPdtId());
            tSpecialPrice.setExecuteType(Integer.valueOf(compete.getBidType()));
            tSpecialPrice.setPrice(competeTender.getWinBidPrice());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startTime = compete.getExecuteStartTime().toString().replace("T"," ").substring(0, 10) + " 00:00:00";
            tSpecialPrice.setStartTime(LocalDateTime.parse(startTime,formatter));
//                    把day改为23：59：59结尾
            String endTime = compete.getExecuteEndTime().toString().replace("T"," ").substring(0, 10) + " 23:59:59";
            tSpecialPrice.setEndTime(LocalDateTime.parse(endTime,formatter));
            tSpecialPrice.setCreateTime(LocalDateTime.now());
            tSpecialPrice.setCreaterId(user.getId());
            tSpecialPrice.setConnId(competeTender.getId());
            tSpecialPrice.setDataFrom(plantId);
            tSpecialPriceService.save(tSpecialPrice);
        }
        tCompeteService.updateById(compete);

        sysLogBu.logRecord("设置定标", user.getTrueName(), "将标题为" + "【+" + title + "】" + "的标的状态设置为定标", plantId);
        return SzResult.Success();
    }

    /**
     * 作废
     */
    public SzResult cancelBid(String id, String reason, String token, String plantId) throws Exception {
        TCompete compete = tCompeteService.getById(id);
        compete.setStatus(30);//作废状态
        if (reason == null || reason.isEmpty()) {
            return SzResult.error("请输入作废理由");
        }
        tCompeteService.updateById(compete);
        sysLogBu.logRecord("竞价作废", userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString()).getTrueName(), "将标题为" + "【+" + compete.getTitle() + "】" + "的标的状态设置为作废" + "作废理由是:" + reason, plantId);
        return null;
    }


    /**
     * 查询竞标品种授权
     */
    public SzResult competePdtAuth(String page, String pageSize, String co, String chiCo, String pdt, String token, String plantId) throws Exception {
        Map<String, Object> map = new HashMap<>();

        if (page != null && !page.isEmpty() && pageSize != null && !pageSize.isEmpty()) {
            Page<TCompetePdtsAuth> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
            QueryWrapper<TCompetePdtsAuth> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(co != null && !co.isEmpty(), "PDTSAUTH_CO", co);
            queryWrapper.eq(chiCo != null && !chiCo.isEmpty(), "PDTSAUTH_CHICO", chiCo);
            queryWrapper.eq(pdt != null && !pdt.isEmpty(), "PDTSAUTH_PDT", pdt);
            queryWrapper.eq("PDTSAUTH_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            queryWrapper.orderByAsc("PDTSAUTH_LOCK");
            queryWrapper.orderByDesc("PDTSAUTH_ID");
            queryWrapper.eq("PDTSAUTH_DELETED", 0);
            List<TCompetePdtsAuth> totalList = tCompetePdtsAuthService.list(queryWrapper);
            Iterator<TCompetePdtsAuth> iterator = totalList.iterator();
            while (iterator.hasNext()) {
                TCompetePdtsAuth tCompetePdtsAuth = iterator.next();
                String pdtsauthCo = tCompetePdtsAuth.getPdtsauthCo();
                String pdtsauthChico = tCompetePdtsAuth.getPdtsauthChico();
                QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("CPY_CO", pdtsauthCo);
                queryWrapper1.eq("CPY_CHICO", pdtsauthChico);
                queryWrapper1.eq("CPY_DELETED", 0);
                CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                if (cCompanys == null) {
                    iterator.remove();
                }
            }
            int total = totalList.size();
            int start = (Integer.parseInt(page) - 1) * Integer.parseInt(pageSize);
            int end = Integer.parseInt(page) * Integer.parseInt(pageSize);
            List<TCompetePdtsAuth> list = new ArrayList<>();
            for (int i = start; i < end && i < total; i++) {
                if (i < totalList.size()) {
                    list.add(totalList.get(i));
                }
            }
            map.put("total", total);
            map.put("list", list);
        } else {
            QueryWrapper<TCompetePdtsAuth> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(co != null, "PDTSAUTH_CO", co);
            queryWrapper.eq(chiCo != null && !chiCo.equals(""), "PDTSAUTH_CHICO", chiCo);
            queryWrapper.eq(pdt != null && !pdt.equals(""), "PDTSAUTH_PDT", pdt);
            queryWrapper.orderByAsc("PDTSAUTH_LOCK");
            queryWrapper.orderByDesc("PDTSAUTH_ID");
            queryWrapper.eq("PDTSAUTH_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            List<TCompetePdtsAuth> list = tCompetePdtsAuthService.list(queryWrapper);
            Iterator<TCompetePdtsAuth> iterator = list.iterator();
            while (iterator.hasNext()) {
                TCompetePdtsAuth tCompetePdtsAuth = iterator.next();
                String pdtsauthCo = tCompetePdtsAuth.getPdtsauthCo();
                String pdtsauthChico = tCompetePdtsAuth.getPdtsauthChico();
                QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("CPY_CO", pdtsauthCo);
                queryWrapper1.eq("CPY_CHICO", pdtsauthChico);
                queryWrapper1.eq("CPY_DELETED", 0);
                CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                if (cCompanys == null) {
                    iterator.remove();
                }
            }
            map.put("total", list.size());
            map.put("list", list);
        }
        return SzResult.success(map);
    }

    /**
     * 删除竞标品种授权
     */
    public SzResult deleteCompetePdtAuth(String id, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        if (user != null) {
            TCompetePdtsAuth competePdtsAuth = tCompetePdtsAuthService.getById(id);
            if (competePdtsAuth != null) {
                String pdtsauthPdt = competePdtsAuth.getPdtsauthPdt();
                QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PDTINF_PDT", pdtsauthPdt);
                queryWrapper.eq("PDTINF_DELETED", 0);
                queryWrapper.eq("DATA_FROM", plantId);
                CProductsInfo cProductsInfo = icProductsInfoService.getOne(queryWrapper);
                String id1 = String.valueOf(cProductsInfo.getPdtinfId());
                QueryWrapper<CTrucks> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("TRUCKS_CHECKIN_PDT", id1);
                queryWrapper1.eq("TRUCKS_DELETED", 0);
                queryWrapper1.eq("DATA_FROM", plantId);
                queryWrapper1.between("TRUCKS_QUEUE_STATUS", 1, 6);
                queryWrapper1.last("limit 1");
                CTrucks cTrucks = icTrucksService.getOne(queryWrapper1);
                if (cTrucks != null) {
                    return SzResult.error("厂内有车辆正在运行，请等待车辆出厂后再操作。");
                }

                competePdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "删除");
                sysLogBu.logRecord("删除竞标品种授权", user.getTrueName(), "删除" + competePdtsAuth.getPdtsauthCo() + "的" + pdtsauthPdt, plantId);
                competePdtsAuth.setPdtsauthDeleted(1);
                competePdtsAuth.setDownedID1(0);
                boolean b = tCompetePdtsAuthService.updateById(competePdtsAuth);
                if (b) {
                    return SzResult.Success();
                } else {
                    return SzResult.error("修改失败");
                }
            } else {
                return SzResult.error("该授权不存在");
            }
        } else {
            return SzResult.error("用户不存在");
        }
    }

    /**
     * 新增竞标品种授权
     */
    public SzResult addCompetePdtAuth(String pdtsauthCo, String pdtsauthChico, String pdtsauthPdt, String pdtsauthPrice, String token, String plantId) throws Exception {
        //根据pdtsauthCo,pdtsauthChico,pdtsauthPdt查询是否已经授权
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TCompetePdtsAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PDTSAUTH_CO", pdtsauthCo);
        queryWrapper.eq("PDTSAUTH_CHICO", pdtsauthChico);
        queryWrapper.eq("PDTSAUTH_PDT", pdtsauthPdt);
        queryWrapper.eq("PDTSAUTH_DELETED", 0);
        List<TCompetePdtsAuth> list = tCompetePdtsAuthService.list(queryWrapper);
        if (!list.isEmpty()) {
            return SzResult.error("该单位已授权该品种，请勿重复授权");
        }
        QueryWrapper<TCompetePdtsAuth> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.orderByDesc("PDTSAUTH_ID");
        queryWrapper1.last("limit 1");
        TCompetePdtsAuth cPdtsAuth1 = tCompetePdtsAuthService.getOne(queryWrapper1);
        TCompetePdtsAuth competePdtsAuth = new TCompetePdtsAuth();
        if (cPdtsAuth1 != null) {
            competePdtsAuth.setPdtsauthId(BigDecimal.valueOf(cPdtsAuth1.getPdtsauthId().intValue() + 1));
        } else {
            competePdtsAuth.setPdtsauthId(BigDecimal.valueOf(1));
        }
        competePdtsAuth.setPdtsauthCo(pdtsauthCo);
        competePdtsAuth.setPdtsauthChico(pdtsauthChico);
        competePdtsAuth.setPdtsauthPdt(pdtsauthPdt);
        if (pdtsauthPrice != null && !pdtsauthPrice.isEmpty()) {
            competePdtsAuth.setPdtsauthPrice(new BigDecimal(pdtsauthPrice));
        }
        competePdtsAuth.setPdtsauthOprtr(user.getTrueName());
        competePdtsAuth.setPdtsauthTime(LocalDateTime.now());
        competePdtsAuth.setDataFrom(plantId);
        competePdtsAuth.setPdtsauthDeleted(0);
        competePdtsAuth.setPdtsauthLock(0);
        competePdtsAuth.setDownedID1(0);
        competePdtsAuth.setPdtsauthReason("授权");
        //该品种绑定的单位就是收款单位
        QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("PDTINF_PDT", pdtsauthPdt);
        queryWrapper3.eq("PDTINF_DELETED", 0);
        CProductsInfo cProductsInfo = icProductsInfoService.getOne(queryWrapper3);
        String pdtinfSubjectId = cProductsInfo.getPdtinfSubjectId();
        if (pdtinfSubjectId == null) {
            return SzResult.error("该品种未绑定单位，请先绑定单位");
        }
        //审批
        QueryWrapper<TApprove> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("IF_ON", 1);
        queryWrapper4.eq("DEL_FLAG", 0);
        queryWrapper4.eq("DATA_FROM", plantId);
        queryWrapper4.eq("APPROVE_NAME", "competePdtAuth");
        TApprove tApprove = tApproveService.getOne(queryWrapper4);

        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的竞标品种授权审批：【" + "将" + pdtsauthPdt + "授权给" + pdtsauthCo + "." + pdtsauthChico + " 单位" + "授权价格为:" + pdtsauthPrice + " 】");
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();
            map.put("competePdtsAuth", competePdtsAuth);
            map.put("pdtinfSubjectId", pdtinfSubjectId);
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            tApproveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }
        tCompetePdtsAuthService.save(competePdtsAuth);
        return SzResult.Success();
    }

    /**
     * 冻结竞标品种授权
     */
    @Transactional
    public SzResult freezePdtAuth(String id, Integer lock, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        if (user != null) {
            TCompetePdtsAuth cPdtsAuth = tCompetePdtsAuthService.getById(id);
            if (cPdtsAuth != null) {
                cPdtsAuth.setPdtsauthLock(lock);
                cPdtsAuth.setDownedID1(0);
                tCompetePdtsAuthService.updateById(cPdtsAuth);
                if (lock == 1) {
                    cPdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "冻结");
                    sysLogBu.logRecord("冻结竞标品种授权", user.getTrueName(), "冻结" + cPdtsAuth.getPdtsauthCo() + "的" + cPdtsAuth.getPdtsauthPdt(), plantId);
                    return SzResult.success("冻结竞标品种授权成功");
                } else {
                    cPdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "解冻");
                    sysLogBu.logRecord("解冻竞标品种授权", user.getTrueName(), "解冻" + cPdtsAuth.getPdtsauthCo() + "的" + cPdtsAuth.getPdtsauthPdt(), plantId);
                    return SzResult.success("解冻竞标品种授权成功");
                }
            } else {
                return SzResult.error("该授权不存在");
            }
        } else {
            return SzResult.error("用户不存在");
        }
    }


    /**
     * 竞标品种导表
     */
    @Async
    public Future<List<CompetePdtAuthExcelEn>> competePdtAuthExportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String plantId, String pdtsauthCo, String pdtsauthPdt) {

        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<CompetePdtAuthExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        CompetePdtAuthExcelEn pdtAuthExcelEn = CompetePdtAuthExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("pdtsauthCo")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthPdt")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPdt(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthPrice")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPrice(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("pdtsauthOprtr")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthOprtr(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthTime")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthReason")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthReason(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthLock")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthLock(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtAuthExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<TCompetePdtsAuth> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like(pdtsauthCo != null && !pdtsauthCo.isEmpty(), "PDTSAUTH_CO", pdtsauthCo);
                    queryWrapper.like(pdtsauthPdt != null && !pdtsauthPdt.isEmpty(), "PDTSAUTH_PDT", pdtsauthPdt);
                    queryWrapper.eq("PDTSAUTH_DELETED", 0);
                    queryWrapper.eq("DATA_FROM", plantId);
                    List<TCompetePdtsAuth> cPdtsAuths = tCompetePdtsAuthService.list(queryWrapper);
                    Iterator<TCompetePdtsAuth> iterator = cPdtsAuths.iterator();
                    while (iterator.hasNext()) {
                        TCompetePdtsAuth tCompetePdtsAuth = iterator.next();
                        String pdtsauthCo1 = tCompetePdtsAuth.getPdtsauthCo();
                        String pdtsauthChico1 = tCompetePdtsAuth.getPdtsauthChico();
                        QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.eq("CPY_CO", pdtsauthCo1);
                        queryWrapper1.eq("CPY_CHICO", pdtsauthChico1);
                        queryWrapper1.eq("CPY_DELETED", 0);
                        CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                        if (cCompanys == null) {
                            iterator.remove();
                        }
                    }
                    for (TCompetePdtsAuth cPdtsAuth : cPdtsAuths) {
                        CompetePdtAuthExcelEn pdtAuthExcelEn = CompetePdtAuthExcelEn.builder()
                                .pdtsauthCo(Optional.of(cPdtsAuth.getPdtsauthCo()+"."+cPdtsAuth.getPdtsauthChico()).orElse(""))
                                .pdtsauthPdt(Optional.ofNullable(cPdtsAuth.getPdtsauthPdt()).orElse(""))
                                .pdtsauthPrice(cPdtsAuth.getPdtsauthPrice())
                                .pdtsauthOprtr(Optional.ofNullable(cPdtsAuth.getPdtsauthOprtr()).map(Object::toString).orElse(""))
                                .pdtsauthTime(Optional.ofNullable(cPdtsAuth.getPdtsauthTime()).map(Object::toString).orElse(""))
                                .pdtsauthReason(Optional.ofNullable(cPdtsAuth.getPdtsauthReason()).map(Object::toString).orElse(""))
                                .pdtsauthLock(Optional.ofNullable(pdtAuthDic.getPdtAuthLockDic(cPdtsAuth.getPdtsauthLock())).orElse(""))
                                .build();
                        list.add(pdtAuthExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        CompetePdtAuthExcelEn pdtAuthExcelEn = CompetePdtAuthExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("pdtsauthCo")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthPdt")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPdt(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthPrice")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPrice(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("pdtsauthOprtr")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthOprtr(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthTime")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthReason")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthReason(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthLock")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthLock(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtAuthExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }
}

